package com.zh.harmony.mvvmharmony.slice;

import com.zh.harmony.livedata.Observer;
import com.zh.harmony.livedatabus.LiveDataBus;
import com.zh.harmony.mvvm.slice.ComponentAbilitySlice;
import com.zh.harmony.mvvmharmony.Constant;
import com.zh.harmony.mvvmharmony.ResourceTable;
import com.zh.harmony.mvvmharmony.ability.LoginAbility;
import com.zh.harmony.mvvmharmony.fragment.PagerSampleAbility;
import com.zh.harmony.mvvmharmony.model.UserInfo;
import com.zh.harmony.mvvmharmony.util.ToastUtil;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;

/**
 * 主页
 */
public class MainSlice extends ComponentAbilitySlice implements Observer<UserInfo> {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_slice_main);
        //登录
        Component loginBtn = findComponentById(ResourceTable.Id_go_login);
        loginBtn.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                LoginAbility.start(getAbility());
            }
        });
        findComponentById(ResourceTable.Id_go_pager_sample).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                PagerSampleAbility.start(getAbility());
            }
        });
        //接收登录事件
        LiveDataBus.get().with(Constant.ACTION_LOGIN_SUCCESS, UserInfo.class)
                .observeForever(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        LiveDataBus.get().with(Constant.ACTION_LOGIN_SUCCESS, UserInfo.class)
                .removeObserver(this);
    }

    @Override
    public void onChanged(UserInfo userInfo) {
        String userName = userInfo.getUserName();
        String password = userInfo.getPassword();
        ToastUtil.toast(getContext(), "登录成功，用户名：" + userName + "，密码：" + password);
    }
}